package com.kzc.twelve.ui;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.kzc.twelve.ApplicationHelper;
import com.kzc.twelve.Config;
import com.kzc.twelve.animation.AnimLayer;
import com.kzc.twelve.entity.Card;
import com.kzc.twelve.ui.CardView.OnSelectListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 画布
 * Created by 柯尊诚 on 2015/12/10.
 * kzc
 */
public class GameCanvas extends LinearLayout{

    CardView[][] cardsMap = new CardView[Config.col][Config.row];

    private List<Point> emptyPoints = new ArrayList<>();
    private OnSelectListener onSelectListener;

    AnimLayer animLayer;

    public GameCanvas(Context context) {
        super(context);
        initGameView();
    }


    public GameCanvas(Context context, AttributeSet attrs) {
        super(context, attrs);
        initGameView();
    }

    public GameCanvas(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initGameView();
    }

    /**
     * 初始化游戏视图
     */
    private void initGameView() {
        setOrientation(LinearLayout.VERTICAL);

        onSelectListener = new CardSelectListener(this, cardsMap, ApplicationHelper.getHelper().getScoreListener());

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Log.d("xxx", "onSizeChanged");

        //获取宽度
        Config.CARD_WIDTH = (Math.min(w, h) - 10) / Config.col;

        if (!ApplicationHelper.getHelper().getScoreListener().initCompletion()) {

            initCards();

            startGame();
        }
    }


    /**
     * 初始化卡片
     */
    protected void initCards() {
        LinearLayout line;
        LayoutParams lineLp;

        //先清除所有
        removeAllViews();

        setGravity(Gravity.CENTER_HORIZONTAL);

        for (int y = 0; y < Config.row; y++) {
            line = new LinearLayout(getContext());
            line.setGravity(Gravity.CENTER_HORIZONTAL);
            lineLp = new LayoutParams(-1, Config.CARD_WIDTH);
            addView(line, lineLp);
            for (int x = 0; x < Config.col; x++) {
                CardView card = new CardView(getContext(), new Card(x, y));
                line.addView(card, Config.CARD_WIDTH, Config.CARD_WIDTH);
                card.setOnSelectListener(onSelectListener);

                cardsMap[x][y] = card;
            }
        }
    }

    public void onRegain(Card[][] cards) {
        regainCards(cards);
    }

    /**
     * 恢复卡片
     */
    private void regainCards(Card[][] cards) {
        LinearLayout line;
        LayoutParams lineLp;

        removeAllViews();

        setGravity(Gravity.CENTER_HORIZONTAL);

        for (int y = 0; y < Config.row; y++) {
            line = new LinearLayout(getContext());
            line.setGravity(Gravity.CENTER_HORIZONTAL);
            lineLp = new LayoutParams(-1, Config.CARD_WIDTH);
            addView(line, lineLp);
            for (int x = 0; x < Config.col; x++) {
                CardView card = new CardView(getContext(), new Card(x, y));
                line.addView(card, Config.CARD_WIDTH, Config.CARD_WIDTH);
                card.setOnSelectListener(onSelectListener);

                cardsMap[x][y] = card;
                cardsMap[x][y].setNum(cards[x][y].getNum());
            }
        }
    }

    public void setAnimLayer(AnimLayer animLayer) {
        this.animLayer = animLayer;
        //添加移动动画完后的事件
        animLayer.setListener(new AnimLayer.AnimationListener() {
            @Override
            public void onAnimationComplete() {
                Log.d("xxx", "onAnimationComplete");
                //移动后添加一个卡片
                addRandomNum(Config.isCombine);
            }
        });
    }

    /**
     * 难度1，移到空白处+1
     * 难度2，移动空白处+2，以此类推
     */
    protected void addRandomNum(boolean isCombine) {
        if (isCombine) {
            addRandomNum();
        } else {
            switch (Config.level) {
                case Config.level_3:
                    addRandomNum();
                case Config.level_2:
                    addRandomNum();
                case Config.level_1:
                    addRandomNum();
            }
        }
    }

    /**
     * 开始游戏
     */
    protected void startGame() {
        //开局默认有三个卡片
        addRandomNum();
        addRandomNum();
        addRandomNum();
    }

    /**
     * 添加随机数字卡片
     */
    protected void addRandomNum() {
        //找出空位置的坐标
        emptyPoints.clear();

        int max = 0;

        for (int y = 0; y < Config.row; y++) {
            for (int x = 0; x < Config.col; x++) {
                int num = cardsMap[x][y].getNum();
                if (num <= 0) {
                    emptyPoints.add(new Point(x, y));
                }

                if (num > max) {
                    max = num;
                }
            }
        }

        Log.d("xxx", "size: " + emptyPoints.size());

        //设置卡片数值,如果有空位，就继续
        if (emptyPoints.size() > 0) {
            Point p = emptyPoints.remove((int) (Math.random() * emptyPoints.size()));
            //根据难度设置数值
            int n = 1;
            switch (Config.level) {
                case Config.level_1:
                    n = (int) (Math.random() * 3 + 1);
                    break;
                case Config.level_2:
                case Config.level_3:
                    n = (int) (Math.random() * (max / Config.level) + Math.random() * 2 + 1);
                    break;
                default:
                    break;
            }
            Log.d("xxx", "Num: " + n + " max: " + max + " level: " + Config.level);
            cardsMap[p.x][p.y].setNum(n);
        }
    }

    /**
     * 结束游戏
     */
    public void endGame() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setMessage("是否重新开始？原因：" + Config.INFO);
        builder.setTitle("游戏结束");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ApplicationHelper.getHelper().getScoreListener().restart();

                initCards();

                startGame();
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getContext(), "好吧！再让你挣扎一下。。。", Toast.LENGTH_SHORT).show();
            }
        });

        builder.create().show();
    }
}
